package com.nb.protocol.service;

import com.nb.protocol.protocol.MessageHolder;
import com.nb.protocol.queue.TaskQueue;
import com.nb.protocol.util.ThreadPoolBuilder;
import org.apache.log4j.Logger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * The implementation of Service.
 *
 * @author Yohann.
 */
public class Service extends Thread {
    private static final Logger logger = Logger.getLogger(Service.class);

    // 任务队列
    final private BlockingQueue<MessageHolder> taskQueue = TaskQueue.getQueue();

    private static final int THREAD_COUNT = 3;//Runtime.getRuntime().availableProcessors();

    public static Service[] _workers;

    public  volatile boolean _stop =false;

    public Service(String name)  {
        super(name);
    }

    public static void initAndStart() {
        startWorker(THREAD_COUNT);
        logger.info("初始化服务完成，THREAD_COUNT="+THREAD_COUNT);
    }

    public static void  startWorker(int workNum) {
        _workers = new Service[workNum];
        for(int i = 0; i < workNum; i++) {
            _workers[i] = new Service("deal-thread-"+i);
            _workers[i].start();
        }
    }

    public static void stopWorkers() {
        for(int i = 0; i < THREAD_COUNT; i++) {
            _workers[i]._stop = true;
        }
    }

    @Override
    public void run() {
        while(!_stop) {
            MessageHolder messageHolder = null;
            try {
                messageHolder = taskQueue.poll(5, TimeUnit.MINUTES);
                if(messageHolder == null){
                    logger.info("TaskQueue未取到任务,taskQueue=" + taskQueue.size());
                    continue;
                }

            } catch (InterruptedException e) {
                logger.error("Caught Exception");
            }
            try {
                assert messageHolder != null;
                logger.info("TaskQueue取出任务: taskQueue=" + taskQueue.size());
                logger.info("开始执行取出的任务 messageHolder=" + messageHolder);
                Dispatcher.dispatch(messageHolder);
                logger.info("任务处理结束");
            } catch (Exception e) {
                logger.error("Caught Exception");
            }
        }
    }

}
